package com.zlp.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.zlp.alipay.config.api.R;
import com.zlp.alipay.dto.OrderReq;
import com.zlp.alipay.dto.RefundReq;
import com.zlp.alipay.service.OrderService;
import com.zlp.alipay.util.AlipayProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支付订单
 *
 * @author ZouLiPing
 * @date 2020/5/12 10:53
 */
@Controller
@RequestMapping("/order")
@Api(value = "OrderController", tags = "订单支付模块")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private AlipayProperties alipayProperties;

    /**
     * 跳转到订单下单页面
     */
    @GetMapping("/goPay")
    public String goPay() {

        return "pay";
    }

    /**
     * 调用支付宝返回支付页面
     *
     * @param orderReq
     * @throws AlipayApiException
     */
    @PostMapping("/pay")
    @ApiOperation(value = "调用支付接口生成支付页面")
    public void pay(OrderReq orderReq, HttpServletResponse httpResponse) throws Exception {

        String payResult = orderService.orderPay(orderReq);
        httpResponse.setContentType("text/html;charset=" + alipayProperties.getCharset());
        httpResponse.getWriter().write(payResult);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
     * 支付成功的跳转页面
     */
    @GetMapping("/goPaySuccPage")
    public String goPaySuccPage() {

        return "paySuccess";
    }

    /**
     * 支付成功的回调接口
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/notifyPayResult")
    public String notifyPayResult(HttpServletRequest request) {

        return orderService.notifyPayResult(request);
    }


    /**
     * 支付退款
     */
    @ResponseBody
    @GetMapping("/refund")
    @ApiOperation(value = "支付退款")
    public R refund(RefundReq refundReq) {

        String result = orderService.refund(refundReq);
        return R.success(result);
    }


}
